#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <time.h>


struct tm *get_time()
{
	time_t sec = time(NULL);
	struct tm *stime = localtime(&sec);
	return stime;
};
//===============================
void delay(int t)
//===============================
{
  t = t*1000; // convert to ms
  usleep(t);
}

//===============================
int startProcess(char* processName)
//===============================
{
   FILE  *out;
   char runCmd[120];
   time_t t;

   time(&t);
   out = fopen("watchdog.log","a");
   sprintf(runCmd,"nohup ./%s &",processName);
   fprintf(out,"Process: %s started %s",processName,ctime(&t));
   system(runCmd);
   fclose(out);
}
//===============================
int processFound(char* processName, char* wrkFile)
//===============================
{
  FILE  *in;
  char  line[128];
  int   found = 0;
   
  in = fopen(wrkFile,"r");
  if(in == NULL)
  {
      printf("Watchdog: Unable to open file %s\n",wrkFile);
  }
  else
  {
    while (fgets(line,sizeof line,in) != NULL)
    {
          if(strstr(line,processName)!= NULL) 
          {
		found++;
          }
    }
    //if(found == 0)printf("Process %s is dead\n",processName);
    //if(found == 1)printf("Process %s is alive\n",processName);
    //if(found  > 1)printf("Process %s multiple %d instances\n",processName,found);
  }
  fclose(in);
  return(found);
}
//===============================
//===============================
int main(int argc, char **argv)
//===============================
//===============================
{
  char process[80],workFile[80],runCmd[120];
  int td = 9999,res = 0;



  if(argc != 3){printf("Usage: watchdog <proc> <time>\n");exit(0);}
  if(argc == 3)
  {
    strcpy(process,argv[1]); 
    sscanf(argv[2],"%d",&td);
    printf("Process %s is watched every %d sec\n",process,td);
    strcpy(workFile,process);
    strcat(workFile,".wrk");
  }
  
  while(1)
  {
	//printf("Watchdog\n");
	sprintf(runCmd,"ps -A > %s",workFile);
	system(runCmd);
	res = processFound(process,workFile);
	if(res == 0)startProcess(process);
	delay(td);
  }
}
